package top.luo.mycat.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author luo
 * @date 2021-03-19 11:24
 */
public class StaticResourceUtils {

    public static final int BUFFER_LENGTH = 1024;

    /**
     * 获取静态资源的绝对路径
     */
    public static String getAbsolutePath(String path) {
        String absolutePath = StaticResourceUtils.class.getResource("/").getPath();
        return absolutePath.replaceAll("\\\\", "/") + path;
    }

    /**
     * 读取文件并 输出
     */
    public static void output(InputStream ins, OutputStream ous) throws IOException {
        int count = 0;
        while (count == 0) {
            count = ins.available();
        }
        int resourceSize = count;
        // 输出http头
        ous.write(HttpProtocolUtils.getHttpHeaderOk(count).getBytes());
        // 读取内容并输出
        long written = 0;
        byte[] bytes = new byte[BUFFER_LENGTH];
        while (written < resourceSize) {
            // 判断本次读操作，一个1024的byte数据能否存储
            if (written + BUFFER_LENGTH > resourceSize) {
                // 剩余的文件大小
                int restSize = (int) (resourceSize - written);
                bytes = new byte[resourceSize];
            }

            int read = 0;
            while (read != -1) {
                read = ins.read(bytes);
            }
            ous.write(bytes);
            ous.flush();

            written += bytes.length;
        }
    }

}
